package com.ruoyi.common.utils.file;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

public class OssUtils {
	private static final String endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
	private static final String accessKeyId = "LTAIjq2s5C390tpR";
	private static final String accessKeySecret = "8JpniDvA9dGITxz0RweyuJAabhyGTz";
	private static final String bucketName = "szsxs";
	private static final String imageBaseUrl = "https://szsxs.oss-cn-shenzhen.aliyuncs.com/";

	public static String upload(InputStream inputStream, String extName) {
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		String fileName = UUID.fastUUID() + "." + extName;
		try {
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName,inputStream);
			ossClient.putObject(putObjectRequest);
			ossClient.shutdown();
		} catch (Exception e) {
			System.out.println("上传图片到阿里云oss存储异常："+e.getMessage());
		}
		return imageBaseUrl + fileName;
	}

	public static String upload(MultipartFile file) throws Exception {
		InputStream inputStream = file.getInputStream();
		String extName = FileUploadUtils.getExtension(file);
		FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
		return upload(inputStream,extName);
	}
}
